<template>
  <div class="content">
    <van-sticky class="nav">
      <van-nav-bar>
        <template #left>
          <van-icon
            name="arrow-left"
            color="#ddd"
            @click="$router.go(-1)"
            size="25px"
          />
        </template>
        <template #right>
          <van-icon
            name="contact"
            color="#ddd"
            @click="$router.go(-1)"
            size="25px"
          />
        </template>
      </van-nav-bar>
    </van-sticky>
    <div class="header">
      <van-uploader
        preview-size="150px"
        class="uploader"
        v-model="fileList"
        multiple
        :max-count="1"
        :after-read="afterRead"
      />
    </div>
    <van-button
      type="primary"
      size="large"
      color="#ffc94b"
      style="
        font-size: 26px;
        margin: 0 10px;
        width: 90%;
        font-weight: bold;
        font-size: 20px;
      "
      @click="submit"
      >修改头像</van-button
    >
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { meApi } from "@/http/apis/meApi";
import { useRoute } from "vue-router";
import { upload } from "@/http/myaxios";
import { useStore } from "vuex";
import router from "@/router";

//获得登录用户数据
const $store = useStore();
const store1 = $store.state.user;
const u_img = store1.u_img;
const u_id = ref(useRoute().params.id); //拿到用户id
const fileList = ref([]); //复显示图片

// 文件上传
let arrFile = ref([]); // 存放上传图片的名字
const afterRead = async (file) => {
  // 此时可以自行将文件上传至服务器
  let fd = new FormData();
  fd.append("uploadInfo", file.file); // uploadInfo是后台定义接收上传文件的名字
  let res = await upload.post(fd);
  // 判断上传成功
  if (res.data.code == 200) {
    res.data.data.forEach((element) => {
      arrFile.value = element.filename;
      // console.log(res.data.code);
    });
  }
};
//修改用户头像
async function submit() {
  let params = { u_id: u_id.value, u_img: arrFile.value };
  let res = await meApi.updateUserHead(params);
  console.log(res);
  if (res.data.code == 200) {
    store1.u_img = arrFile.value;
    // console.log("123", store1.u_img);
    $store.commit("saveUserInfo", store1);
    router.push("/home/me");
  }
}
</script>

<style lang="scss" scoped>
.header {
  width: 90%;
  position: relative;
  left: 50%;
  transform: translateX(-25%);
  margin-top: 20px;

  .uploader {
    border-radius: 50px;
  }
}
</style>
